package cn.tedu.sp11.fallback;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import cn.tedu.web.util.JsonResult;


@Component
public class ItemFallback implements FallbackProvider {
	//决定哪个微服务调用该降级类
	@Override
	public String getRoute() {
//		return null;//所有微服务都可以调用该降级类
//		return "*"; //所有微服务都可以调用该降级类
		return "item-service";
	}
	//fallbackResponse():返回值类型是ClientHttpResponse，封装了返回的状态码，状态文本，msg
	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
		return new ClientHttpResponse() {
			//添加协议头: content-type:application/json
			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders httpHeaders = new HttpHeaders();
				httpHeaders.setContentType(MediaType.APPLICATION_JSON);
				return httpHeaders;
			}
			//具体提示信息
			@Override
			public InputStream getBody() throws IOException {
				//JsonResult：{code,msg,data}
				String json = JsonResult.err("服务器正在维护中，请稍后再试~~").toString();
				return new ByteArrayInputStream(json.getBytes("utf-8"));
			}
			//HttpStatus：封装了状态码和状态文本
			@Override
			public HttpStatus getStatusCode() throws IOException {
				return HttpStatus.OK;//OK中封装了code、text {200,"OK"}
			}
			@Override
			public String getStatusText() throws IOException {
				return HttpStatus.OK.getReasonPhrase(); //状态文本
			}
			
			@Override
			public int getRawStatusCode() throws IOException {
				return HttpStatus.OK.value(); //状态码
			}
			
			@Override
			public void close() {
			}
		};
	}
}

